package com.midou.administration.Interceptor;


import com.midou.administration.entity.Function;
import com.midou.administration.entity.RoleFunction;
import com.midou.administration.service.FunctionService;
import com.midou.administration.service.RoleFunctionService;
import com.midou.administration.service.RoleService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    private RoleFunctionService roleFunctionService;

    private FunctionService functionService;

    private List<RoleFunction> roleFunctions;

    private List<Function> functions;

    public AuthorityInterceptor(){

    }
    public AuthorityInterceptor(RoleFunctionService roleFunctionService,FunctionService functionService){
        this.roleFunctionService = roleFunctionService;
        this.functionService = functionService;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getServletPath();//获取请求路径
        System.out.println(path);
        if (request.getHeader("root").equals("root")){
            return true;
        }
        if (path.equals("/administration/clerk/login")){
            return true;
        }else{
            Integer clerkid = Integer.parseInt(request.getHeader("clerk-id"));
            roleFunctions = roleFunctionService.queryRolePermissions(clerkid);
            functions = functionService.queryFunction(roleFunctions);
            for (Function function : functions) {
                if (function.getFuUrl().equals("#")){
                    return true;
                }
                if (path.equals(function.getFuUrl())){
                    return true;
                }
            }
            Integer count = functionService.queryAllFunction(path);
            if (count<=0){
                return true;
            }else{
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print(false);
                return false;
            }
        }
    }
}
